<template>
  <div class="app-container">
    <div>
      <el-row class="admin-top-g">

        <br>

        <el-row class="common-row">
          <template v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length">
            <el-input v-model="keyword" clearable style="width: 160px;" placeholder="请输入关键字" @keyup.native.enter="searchUser" @change="searchUser"/>
            <!-- <el-date-picker
              v-model="fzhejiu"
              style="width: 145px;"
              type="year"

              placeholder="选择折旧年度"
              @change="selectPeriod"/> -->

            <el-select v-model="fbrand" class="select_el" clearable filterable placeholder="请选择品牌" @change="searchUser">
              <el-option
                v-for="item2 in brandList"
                :key="item2.finterid"
                :label="item2.fname"
                :value="item2.fname"/>
            </el-select>

            <!-- <el-select v-model="youqiVal" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in youQiOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->

            <el-button v-if="isBtn" type="danger" icon="el-icon-check" @click="calculate">计算</el-button>
            <el-button v-else type="success" icon="el-icon-news" @click="saveWage">保存</el-button>
            <el-button type="success" icon="el-icon-back" @click="back">返回</el-button>

          </template>

          <!-- <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新 </el-button> -->

        </el-row>
    </el-row></div>
    <br>
    <el-table
      v-loading="listLoading"
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :data="tableData"
      :header-cell-style="tableHeaderStyle"
      max-height="750"
      class="tableCss"
      element-loading-text="正在加载"
      border
      highlight-current-row
      @cell-dblclick="editData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"/>
      <template v-for="item in formThead">
        <el-table-column v-if="item.frpttypeflag ==0" :key="item.fid" :prop="item.frepfld" :label="item.frepcap" :width="item.frepwid" align="center" show-overflow-tooltip>

          <template slot-scope="scope">
            <template v-if="item.frephide<=0">
              <template v-if="item.frepfld === 'fstatus'">
                <el-tag v-if="Number(scope.row[item.frepfld]) === 1" size="mini" type="success">已审</el-tag>
                <el-tag v-else size="mini" type="danger">未审</el-tag>
              </template>
              <!-- 售后成本 -->
              <div v-else-if="row === scope.row.fsalecost && col==scope.column.id">
                {{ scope.row }}
                <el-input v-model="tmpRow[item.frepfld]" size="mini" @blur="updateUserInfo"/>
              </div>
              <!-- 折旧 -->
              <div v-else-if="row === scope.row.fzhejiu && col==scope.column.id">
                <el-input v-model="tmpRow[item.frepfld]" size="mini" @blur="updateUserInfo"/>
              </div>
              <!-- 运保费 -->
              <div v-else-if="row === scope.row.orderId && col==scope.column.id">
                <el-input v-model="tmpRow[item.frepfld]" size="mini" @blur="updateUserInfo"/>
              </div>
              <template v-else size="mini">
                {{ scope.row[item.frepfld] }}
              </template>
            </template>
          </template>

        </el-table-column>
      </template>
    </el-table>

    <!-- <el-pagination
      v-if="limits.length >=1 && limits.filter(it => it.FName === '查看').length"
      :total="total"
      :page-sizes="pagesizes"
      :page-size="pagesize"
      :current-page.sync="currentPage"
      class="jy-pagination"
      style="text-align: center; margin-top: 20px;"
      background
      layout="sizes, prev, pager, next, total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/> -->
    <el-dialog
      v-el-drag-dialog
      :visible.sync="detailSettings.fdetailModal"
      :close-on-click-modal="false"
      title="详情"
      class="config-dialog">
      <el-table
        v-loading="detailSettings.fdetailLoading"
        ref="fdetailTable"
        :header-cell-style="tableHeaderStyle"
        :data="detailSettings.fdetailData"
        style="margin-top: 10px;"
        max-height="500"
        class="tableCss"
        element-loading-text="正在加载"
        border
        highlight-current-row>
        <el-table-column
          v-for="(item, key) in detailSettings.detailFormThead"
          :key="key"
          :prop="item"
          :label="item"
          align="center">
          <template slot-scope="scope">{{ scope.row[item] }}</template>
        </el-table-column>
      </el-table>
      <!--
      <br>
      <el-pagination
        :total="detailSettings.total"
        :page-sizes="detailSettings.pagesizes"
        :page-size="detailSettings.pagesize"
        :current-page.sync="detailSettings.currentPage"
        class="jy-pagination"
        style="text-align: center; margin-top: 20px;"
        background
        layout="sizes, prev, pager, next, total"
        @size-change="detailSizeChange"
        @current-change="detailCurrentChange"/>
         -->
    </el-dialog>
  </div>
</template>
<script>
let FRepKey = ''
let opername = ''
const defaultFormThead = []

import HeadTable from '../salary/headTable/index.vue'
import { configColumn, yuSuanZLC, yuSuanZLCSave } from '../../api/salary'
import { download } from '../../mixins/download.js'
import { common } from '../../mixins/common'
import { brand } from '../../mixins/brand'
import { pagination } from '../../mixins/pagination'
import { parseTime, getYearYYYY } from '../../utils/index'
import { tableConfig, apiSql, apiFileSave, getCBData } from '../../api/account'

import '../../styles/common.scss'

export default {
  name: 'Index',
  components: {
    HeadTable
  },
  filters: {
    parseTime(time, type) {
      return parseTime(time, type)
    }
  },
  mixins: [download, common, pagination, brand],
  data() {
    return {
      row: '',
      col: '',
      tempRow: {},
      isBtn: true,
      value: '',
      options: [],
      FRepKey: '',
      keyword: '',
      fzhejiu: '',
      fdeleted: '',
      fdeletedList: [

      ],
      youQiOptions: [{
        value: '0',
        label: '经营报价'
      }, {
        value: '1',
        label: '合同报价'
      }],
      youqiVal: '0',

      fdeletedListDiaL: [

      ],
      gapTime: '',
      start_time: '',
      end_time: '',

      // 表头、表格设置
      tableData: [],
      tableList: [],
      defaultFormThead: [],
      formThead: defaultFormThead,
      dialogThead: [],
      curData: {},

      listLoading: false,
      list: [],
      configModal: false,
      configLoading: false,

      loadingForm: false,
      configList: [],
      key: 0,
      // SQL弹窗
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {

      },

      form: {},
      rules: {

      },
      addUserModal: false,
      // loadingForm: false

      fileList: [],

      // 批量删除
      checkData: [],
      selectedData: [],
      rows: [],

      // 用户菜单
      menusList: [],
      limits: [],
      userKey: '',
      fmofanName: '',

      upData: {},
      fdeptname: '', // 部门
      bmList: [], // 部门
      xlList: [], // 学历
      zwList: [], // 职务
      xbList: [], // 性别
      lzztList: [],
      fileListBasic: [],
      baseList: [],
      upDataBasic: {},

      // 明细
      detailSettings: {
        fmodel: '',
        fbrand: '',
        fbrandList: [
          { label: 'WINGD', value: 'WINGD' },
          { label: 'MAN', value: 'MAN' }
        ],
        fdanweibumen: '0',
        fdanweibumenList: [
          { label: '采购部', value: '1' },
          { label: '技术中心', value: '2' },
          { label: '其他部门', value: '3' },
          { label: '全部', value: '0' }
        ],
        keyword: '',
        fdetailModal: false,
        fdetailKeyword: '',
        fdetailLoading: false,
        detailFormThead: [],
        fdetailData: [],
        // 页脚
        total: 0,
        pagesize: 10,
        pagesizes: [10, 20, 50, 100],
        currentPage: 1
      },

      detail: '',
      opername: '',
      detailVisible: false,
      editText: false,
      tableSetExcel: false,
      lookSetShow: false

    }
  },
  async mounted() {
    this.userKey = this.$route.meta.FRepKey
    FRepKey = this.$route.meta.FRepKey
    this.upDataBasic.db = this.globalDb.db
    opername = decodeURIComponent(this.globalDb.fname)
    this.opername = decodeURIComponent(this.globalDb.fname)

    this.upDataBasic.FRepKey = this.$route.meta.FRepKey
    this.lookSetShow = JSON.parse(localStorage.getItem('flookSet'))

    this.upData.db = this.globalDb.db
    this.fmofanName = this.$route.meta.title

    await this.getAllData()

    // 菜单列表（权限）
    const menuRes = JSON.parse(localStorage.getItem('setMenuData'))
    this.menusList = menuRes
    if (menuRes.length >= 1) {
      menuRes.map(it => {
        it.children.map(item => {
          if (item.fobjectid === this.userKey) {
            this.$set(this, 'limits', item.child)
          }
        })
      })
    }
  },
  methods: {
    async detailSizeChange(val) {
      this.detailSettings.currentPage = 1
      this.detailSettings.pagesize = val
      await this.getCBDataList()
    },
    async detailCurrentChange(val) {
      this.detailSettings.currentPage = val
      await this.getCBDataList()
    },
    async searchFmodel() {
      await this.getCBDataList()
    },
    async getCBDataList() {
      try {
        this.detailSettings.fdetailLoading = true
        const res = await getCBData({
          db: this.globalDb.db,
          opername,
          fmodel: this.detailSettings.fmodel,
          fbrand: this.detailSettings.fbrand,
          keyword: this.detailSettings.keyword,
          fdanweibumen: this.detailSettings.fdanweibumen,
          // FRepKey: 26009
          all: 1
          // $fmodel =   $request ->fmodel;
          // $fbrand = $request ->fbrand??'WINGD';
          // $keyword =   $request ->keyword;
          // $fdanweibumen = $request ->fdanweibumen;
          // $FRepKey = $request ->FRepKey;
        })
        if (res.Error === 0) {
          if (res.Data.length) {
            this.detailSettings.detailFormThead = Object.keys(res.Data[0])
          } else {
            this.detailSettings.detailFormThead = []
          }
          setTimeout(() => {
            this.detailSettings.fdetailData = res.Data
          }, 0)
          // console.log(this.formThead, ' this.formThead')
        }
        // this.key = FRepKey
        this.detailSettings.fdetailLoading = false
      } catch (error) {
        this.detailSettings.fdetailLoading = false
      }
    },
    async editData(row, column, cell, event) {
      if (column.property === 'ftaxsinglezjcl') {
        this.detailSettings.fmodel = row.fmodel
        this.detailSettings.fbrand = row.fbrand
        this.detailSettings.fdetailModal = true
        await this.getCBDataList()
      }
      console.log(column.id, column.property, column, row, event, 'column')
      // 如果这里只想编辑某一列或几列判断一下就行：column.label === '列1'
      if (column.property === 'fyunfei' || column.property === 'fsalecost' || column.property === 'fzhejiu') {
        // 取出单元格的值
        // fyunfei 运保费
        // fsalecost 售后成本
        // fzhejiu 折旧
        // console.log(event.target.textContent.trim(), ' event.target.textContent')
        var beforeVal = event.target.textContent.trim()
        // 置空单元格容器内元素
        event.target.innerHTML = ''
        // 替换成el-input
        const str = `<div class='cell'>
            <div class='el-input'>
              <input type='text' placeholder='请输入内容' class='el-input__inner'>
            </div>
        </div>`
        cell.innerHTML = str
        //  获取双击后生成的input  根据层级嵌套会有所变化
        const cellInput = cell.children[0].children[0].children[0]
        cellInput.value = beforeVal
        cellInput.focus() // input自动聚焦
        // "TITLE_PROPER"
        // 失去焦点后  将input移除
        cellInput.onblur = () => {
          const onblurCont = `<div class='cell'>${cellInput.value}</div>`
          // cell.innerHTML = onblurCont // 换成原有的显示内容
          console.log(cellInput.value, ' cellInput.value onblur')
          console.log(cell.innerHTML, ' cell.innerHTML onblur')
          this.$set(cell, 'innerHTML', onblurCont)
          this.$set(row, 'fyunfei', cellInput.value)
        }
      }
    },

    updateUserInfo() {

    },
    calculate() {
      this.getBodyData()
    },
    searchUser() {
      this.getBodyData()
    },
    // 保存
    async saveWage() {
      if (this.selectedData.length <= 0) {
        this.$message({
          message: '请选中表格记录，再保存',
          type: 'warning'
        })
        return
      }
      try {
        this.listLoading = true
        const res = await yuSuanZLCSave({
          db: this.globalDb.db,
          opername,
          FRepKey,
          selectedData: this.selectedData
        })
        this.listLoading = false

        if (res.Error === 0) {
          this.$router.push('/jybj/jybj')
        }
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },
    back() {
      this.$router.push('/jybj/jybj')
    },

    // 刷新
    refresh() {
      window.location.reload()
    },

    async toDetail(data) {
      this.detailVisible = true
      this.detail = data
    },

    async getAllData() {
      // await this.getBodyData()
      await this.getHeadData()
    },

    selectSettings(val) {
      if (val === 0) {
        this.settings()
      } else if (val === 1) {
        this.dialogSQL()
      }
    },
    settings() {
      this.configModal = true
      this.getTableConfig()
    },

    // 更新数据
    async getUpdateConfigData() {
      await this.getTableConfig()
      await this.getBodyData()
      await this.getHeadData()
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername,
          FRepKey
        })

        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        // console.log(error)
      }
    },

    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = opername
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            // console.log(error)
          }
        } else {
          return false
        }
      })
    },

    async getTableConfig() {
      try {
        this.configLoading = true
        const res = await tableConfig({
          db: this.globalDb.db,
          opername,
          key: FRepKey
        })
        this.configList = res.Data
        this.key = FRepKey
        this.configLoading = false
      } catch (error) {
        this.configLoading = false
      }
    },

    // 表头数据
    async getHeadData() {
      try {
        this.listLoading = true
        this.header = []
        this.headerKeys = []
        this.listData = []
        const res = await configColumn({
          db: this.globalDb.db,
          opername,
          FRepKey
        })
        this.listLoading = false
        this.formThead = res.Data
        // this.tableList = []
        this.formThead.map(item => {
          this.tableList.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        // this.tableData = this.tableList.slice()

        // 获取显示表头键值对
        this.formThead.filter(item => {
          if (!item.frephide) {
            this.header.push(item.frepcap)
            this.headerKeys.push(item.frepfld)
          }
        })
        // 获取显示表体数据
        // const listData = this.tableList.slice()
        // listData.map((item, index) => {
        //   this.listData[index] = {}
        //   this.headerKeys.map(it => {
        //     this.listData[index][it] = item[it]
        //   })
        // })

        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'fid') {
            arr.splice(index, 1)
          }
        })

        this.dialogThead = arr.filter(item => item.funcontrol !== 1)
      } catch (error) {
        this.listLoading = false
      }
    },

    // 表体数据————erp职员列表
    // 表体数据  计算数据
    async getBodyData() {
      try {
        this.listLoading = true
        const res = await yuSuanZLC({
          db: this.globalDb.db,
          keyword: this.keyword,
          opername,
          fbrand: this.fbrand,
          fsheji: this.youqiVal

        })

        if (res.Error === 0) {
          this.isBtn = false
          this.$message({
            message: res.Message,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.Message,
            type: 'warning'
          })
        }
        this.formThead.map(item => {
          res.Data.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.tableData = res.Data.slice()

        this.listLoading = false
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },

    selectPeriod(val) {
      this.fzhejiu = getYearYYYY(val)
      // console.log(this.fzhejiu, val, '  this.qjValue')
      // this.searchUser()
    },

    handleSelectionChange(val) {
      console.log(val, ' val handleSelectionChange')
      this.selectedData = val
    }

  }
}

</script>
<style lang="scss" scoped>
.config-dialog ::v-deep .el-dialog {
  width: 90%;
}
 .config-dialog ::v-deep .el-dialog__body {
  padding: 0 20px;
  height: 600px;
 }
</style>
